#-*- coding:utf-8 -*-

# The MIT License (MIT)
# 
# Copyright (c)  2014  Li Lin  <jzqlin@gmail.com>
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


from datetime import datetime 
from time import time

REDIS_REGISGER_VERIFY_QUEUE_KEY = "register_verify_queue"

class Register(object):
    """Register checks and saves the new user's register information.
    """
    
    E_REGISTER_OK = 0
    E_DUPLICATED_ACCOUNT = -100    
    
    
    @staticmethod
    def configure_cache(redis_verify_queue):
        """Configure a redis cache as a register verify queue"""
        Register.redis_verify_queue = redis_verify_queue
    
    
    def __init__(self, ua_user_basic_databases, ua_user_basic_classes):
        self.ua_user_basic_databases = ua_user_basic_databases        
        self.ua_user_basic_classes = ua_user_basic_classes
        self.redis_verify_queue = Register.redis_verify_queue
    
        
    def register(self, account, name, email, phone, password, third_type = 0, third_id = ''):       
        """Do the register things. 
        Put the verify request to a verify queue.
        """ 
        UserBasic = self.ua_user_basic_classes.get_class(account)  
                              
        session = self.ua_user_basic_databases.get_session(account)
        
        user = session.query(UserBasic).filter(UserBasic.account == account).first()
        if user != None:
            # error: account has been registered
            return Register.E_DUPLICATED_ACCOUNTS
        
        user = UserBasic()
        user.account = account
        user.name = name
        user.email = email
        user.phone = phone
        user.password = password
        user.verified = 0  
        user.register_time = datetime.fromtimestamp(time())
        user.third_type = third_type
        user.third_id = third_id
        session.add(user)
        session.commit()
        
        #TODO: The email verify module is not consider temporary, so we don't need to 
        #      put an item to the verify queue 
        #self.__queue_verify_request(user)
        
        return Register.E_REGISTER_OK
    
    
    def __queue_verify_request(self, user):
        """Put a verify request to the verify queue.
        Verify server will process the request and send a verify email to the user's email address.
        """
        
        item = VerifyQueueItem()
        item.account = user.account
        item.email = user.email
        item.register_time = user.register_time
        # Notice: key for the redis queue
        queue_key = "register_verify_queue"
                
        self.redis_verify_queue.rpush(queue_key, item.to_string())
        
 
        

class VerifyQueueItem(object):
    """Queue object for the register verify queue.
    """
    
    def __init__(self):
        self.account = None
        self.email = None
        self.register_time = None
        
    def to_string(self):        
        return "%s|%s|%s" % (self.account, self.email, time.mktime(self.register_time.timetuple()))
    
    def from_string(self, string):
        [self.account, self.email, timestamp_string] = string.split("|")
        self.register_time = datetime.fromtimestamp(float(timestamp_string))        
        
        
